package com.amoby.main.action.tranfer;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amoby.base.common.BaseAction;
import com.amoby.base.common.Pager;
import com.amoby.base.utils.ExcelUtils;
import com.amoby.main.entity.Cbabill;
import com.amoby.main.entity.SysUsers;
import com.amoby.main.service.BillOperation;
import com.amoby.main.service.CbaBillService;
import com.amoby.main.service.CbaMgrService;

/**
 * @date 2015-7-6 下午3:12:31
 * @author zhaoyy
 * @version V1.0
 * @Description 转账日志
 * 
 */
@Controller
public class CbaBillAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(CbaBillAction.class);
    @Autowired
    private CbaMgrService       cbaMgrService;
    @Autowired
    private CbaBillService      cbaBillService;

    /**
     * 初始化页面
     * @author Lasing 2016-5-26 上午10:06:10
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/menus/cbabill_mgr.html", method = RequestMethod.GET)
    public String indexPage(HttpServletRequest request, ModelMap model) {
        return AD_HTML + "tranfer/cbabill_mgr";
    }

    /**
     * 转账列表
     * @author Lasing 2016-5-26 上午10:11:23
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/tranfer/list")
    public Object list(HttpServletRequest request, ModelMap model) throws Exception {
        Pager pager = createPager(request);
        pager.addParam("lodgementRef", getRequestParams(String.class, request, "lodgementRef"));
        pager.addParam("bsId", getRequestParams(String.class, request, "bsId"));
        pager.addParam("channelName", getRequestParams(String.class, request, "channelName"));
        pager.addParam("businessName", getRequestParams(String.class, request, "businessName"));
        pager.addParam("state", getRequestParams(String.class, request, "state"));
        pager.addParam("timeType", getRequestParams(String.class, request, "timeType"));
        pager.addParam("timeFrom", getRequestParams(String.class, request, "timeFrom"));
        pager.addParam("timeEnd", getRequestParams(String.class, request, "timeEnd"));
        cbaMgrService.loadCbabillPage(pager);
        return getGridData(pager);
    }

    /**
     * 详情
     * @author Lasing 2016-5-26 上午11:29:19
     * @param item
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/tranfer/upd.html", method = RequestMethod.POST)
    public Object saveItem(Cbabill item, HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        try {
            SysUsers user = getUser();
            item = cbaMgrService.saveCbabill(item, user);
            result.put(RESULT, true);
            result.put(MESSAGE, "保存成功");
        } catch (IllegalArgumentException e) {
            logger.error("操作失败，参数有误", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "操作失败，输入参数有误！");
        } catch (DuplicateKeyException e) {
            logger.error("保存失败， 数据重复", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "保存失败， 数据已存在！");
        } catch (Exception e) {
            logger.error("保存失败", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "保存失败");
            result.put("exception", e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/cbabill_mgr/allow.save", method = RequestMethod.POST)
    public Object saveAllow(Long billId, HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        try {
            // Long billId = item.getId();
            if (billId == null) {
                throw new IllegalArgumentException("参数有误");
            }
            cbaBillService.flowBill(billId, BillOperation.allow);
            result.put(RESULT, true);
            result.put(MESSAGE, "保存成功");
        } catch (IllegalArgumentException e) {
            logger.error("操作失败，参数有误", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "操作失败，输入参数有误！");
        } catch (Exception e) {
            logger.error("保存失败", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "保存失败");
            result.put("exception", e.getMessage());
        }
        return result;
    }

    // 暂停转账
    @ResponseBody
    @RequestMapping(value = "/cbabill_mgr/stop.save", method = RequestMethod.POST)
    public Object saveStop(Long billId, HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        try {
            if (billId == null) {
                throw new IllegalArgumentException("参数有误");
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("billId", billId);
            map.put("state", 0);
            cbaBillService.updateIsActive(map);
            result.put(RESULT, true);
            result.put(MESSAGE, "暂停成功");
        } catch (IllegalArgumentException e) {
            logger.error("操作失败，参数有误", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "操作失败，输入参数有误！");
        } catch (Exception e) {
            logger.error("暂停失败", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "暂停失败");
            result.put("exception", e.getMessage());
        }
        return result;
    }

    // 激活
    @ResponseBody
    @RequestMapping(value = "/cbabill_mgr/active.save", method = RequestMethod.POST)
    public Object saveActive(Long billId, HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        try {
            if (billId == null) {
                throw new IllegalArgumentException("参数有误");
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("billId", billId);
            map.put("state", 1);
            cbaBillService.updateIsActive(map);
            result.put(RESULT, true);
            result.put(MESSAGE, "激活成功");
        } catch (IllegalArgumentException e) {
            logger.error("操作失败，参数有误", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "操作失败，输入参数有误！");
        } catch (Exception e) {
            logger.error("激活失败", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "激活失败");
            result.put("exception", e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/cbabill_mgr/processed.save", method = RequestMethod.POST)
    public Object saveProcessed(Cbabill item, HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        try {
            Long billId = item.getId();
            if (billId == null) {
                throw new IllegalArgumentException("参数有误");
            }
            if (item.getState() == 5) {
                cbaBillService.flowBill(billId, BillOperation.failHandle);
            } else {
                cbaBillService.flowBill(billId, BillOperation.processed);
            }
            result.put(RESULT, true);
            result.put(MESSAGE, "保存成功");
        } catch (IllegalArgumentException e) {
            logger.error("操作失败，参数有误", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "操作失败，输入参数有误！");
        } catch (Exception e) {
            logger.error("保存失败", e);
            result.put(RESULT, false);
            result.put(MESSAGE, "保存失败");
            result.put("exception", e.getMessage());
        }
        return result;
    }
    
    /**
     * 导出转账列表
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "/tranferExport.html", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lodgementRef", getRequestParams(String.class, request, "lodgementRef"));
        map.put("channelName", getRequestParams(String.class, request, "channelName"));
        map.put("bsId", getRequestParams(String.class, request, "bsId"));
        map.put("businessName", getRequestParams(String.class, request, "businessName"));
        map.put("state", getRequestParams(String.class, request, "state"));
        map.put("timeType", getRequestParams(String.class, request, "timeType"));
        map.put("timeFrom", getRequestParams(String.class, request, "timeFrom"));
        map.put("timeEnd", getRequestParams(String.class, request, "timeEnd"));
        List<Map<String, Object>> lists = cbaMgrService.exportAll(map);
        exports(lists, request, response,getRequestParams(String.class, request, "timeFrom"),getRequestParams(String.class, request, "timeEnd"));
    }

    /**
     * 导出转账列表
     * @param lists
     * @param request
     * @param response
     */
    @SuppressWarnings("rawtypes")
    private void exports(List<Map<String, Object>> lists, HttpServletRequest request, HttpServletResponse response,String startDate,String endDate) {
        List<List<Comparable>> listData = new ArrayList<List<Comparable>>();
        NumberFormat nt = NumberFormat.getPercentInstance();
        // 设置百分数精确度1即保留两位小数
        nt.setMinimumFractionDigits(1);
        // 增加标题行
        listData.add(setHeader());
        for (int i = 0; i < lists.size(); i++) {
            Map<String, Object> map = lists.get(i);
            List<Comparable> list = new ArrayList<Comparable>();
            list.add(map.get("lodgementRef").toString());
            if (map.get("channelName") != null) {
                list.add(map.get("channelName").toString());
            } else {
                list.add("");
            }
            if (map.get("businessName") != null) {
                list.add(map.get("businessName").toString());
            } else {
                list.add("");
            }
            list.add(map.get("amount").toString());
            list.add(map.get("crtime").toString());
            list.add(map.get("uptime").toString());
            list.add(map.get("state").toString());
            listData.add(list);
        }
        String fileName ="";
        if (startDate != null && endDate != null) {
            startDate = startDate.replaceAll("-。", ".");
            endDate = endDate.replaceAll("-", ".");
            if(startDate.equals(endDate)){
                fileName = "tranfer_"+startDate+"_";
            }else{
                fileName = "tranfer_"+startDate+"-"+endDate+"_";
            }
        }else{
            fileName = "tranfer_";
        }
       ExcelUtils.createExcel(request, response, logger, listData, fileName);
    }

    /**
     * 自定义标题栏
     * @return
     */
    @SuppressWarnings("rawtypes")
    private List<Comparable> setHeader() {
        List<Comparable> list = new ArrayList<Comparable>();
        list.add("流水号");
        list.add("所属渠道");
        list.add("转账商户");
        list.add("转账金额");
        list.add("创建时间");
        list.add("结束时间");
        list.add("状态");
        return list;
    }

}
